//
//  SavePlayerViewController.m
//  Cup
//
//  Created by dllo on 15/4/29.
//  Copyright (c) 2015年 doll. All rights reserved.
//

#import "SavePlayerViewController.h"
#import "dataBaseHandle.h"
#import "SavePlayerViewCell.h"
#import "RadioDetailInfoViewController.h"
#import "RadioDetailInfoViewController.h"
#define WIDTH self.view.frame.size.width
@interface SavePlayerViewController ()
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)NSMutableArray *arr;
@property(nonatomic, assign)BOOL isWobble;
@end

@implementation SavePlayerViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"电台音乐收藏";
        self.isWobble = NO;
    }
    return self;
}

- (void)turnBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui"] style:UIBarButtonItemStylePlain target:self action:@selector(turnBack)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:59/255.0 green:54/255.0 blue:24/255.0 alpha:1];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    flowLayout.itemSize = CGSizeMake(WIDTH/4 - 15, WIDTH/4);
    
    flowLayout.minimumLineSpacing = 30;
    flowLayout.minimumInteritemSpacing = 1;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor brownColor];
 
    UIImageView *backimage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    UIImage *imager = [UIImage imageNamed:@"savecup.png"];
    backimage.image = imager;
    [self.collectionView setBackgroundView:backimage];
    //背景图片用户交换打开
    backimage.userInteractionEnabled = YES;
    [self.view addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAcion:)];
    [backimage addGestureRecognizer:tap];
    
    self.arr = [NSMutableArray array];
    [[dataBaseHandle shareDB] openDB];
    self.arr  = [[dataBaseHandle shareDB] selectPlayer];
    
#pragma mark collectionView 采用注册的方式生成cell
    [self.collectionView registerClass:[SavePlayerViewCell class] forCellWithReuseIdentifier:@"reuse"];

//设置导航栏右键清空按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"drop"] style:UIBarButtonItemStylePlain target:self action:@selector(clickRightBu)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:59/255.0 green:54/255.0 blue:24/255.0 alpha:1];
}
- (void)clickRightBu
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定清空收藏内容" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [[dataBaseHandle shareDB] openDB];
        [[dataBaseHandle shareDB] creatPlayerTable];
        [[dataBaseHandle shareDB] dropPlayerTable];
        [self.arr removeAllObjects];
        [self.collectionView reloadData];
    }
}

- (void)tapGestureAcion:(UITapGestureRecognizer *)tap
{
    self.isWobble = NO;
    [self.collectionView reloadData];
}

-(void)BeginWobbleForCell:(UICollectionViewCell *)cell
{
    srand([[NSDate date] timeIntervalSince1970]);
    float rand=(float)random();
    CFTimeInterval t=rand*0.0000000000001;
    [UIView animateWithDuration:0.01 delay:t options:0  animations:^
     {
         cell.transform=CGAffineTransformMakeRotation(-0.05);
     } completion:^(BOOL finished)
     {
         [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse|UIViewAnimationOptionAllowUserInteraction  animations:^
          {
              cell.transform=CGAffineTransformMakeRotation(0.05);
          } completion:^(BOOL finished) {}];
     }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SavePlayerViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    cell.playImage.userInteractionEnabled = YES;
    cell.namelabel.text = [self.arr[indexPath.row]title];
    cell.namelabel.textAlignment = NSTextAlignmentCenter;
    NSURL *url = [NSURL URLWithString:[self.arr[indexPath.row] imgUrl]];
    [cell.playImage sd_setImageWithURL:url];
    cell.playImage.layer.cornerRadius = cell.playImage.frame.size.width/2;
    cell.playImage.clipsToBounds = YES;
    //创建手势
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    //设置长按所需的最短时间
    longPress.minimumPressDuration = 1;
    [cell.playImage addGestureRecognizer:longPress];
    [longPress release];
    if (self.isWobble) {
        cell.deleteimage.image = [UIImage imageNamed:@"iconfont-chahao"];
        [self BeginWobbleForCell:cell];
    }else{
        cell.deleteimage.image = nil;
    }
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.isWobble) {
        RadioDetailInfoViewController *radioVC = [[RadioDetailInfoViewController alloc] init];
        radioVC.tingid = [self.arr[indexPath.row]musicid];
        [self.navigationController pushViewController:radioVC animated:YES];
    }else{
        NSLog(@"开始删除 ");
        //在晃动中,再次点击删除
        PlayInfo *playinfo = self.arr[indexPath.row];
        //打开数据库
        [[dataBaseHandle shareDB] openDB];
        //打开表
        [[dataBaseHandle shareDB] creatPlayerTable];
        //删除动漫数据
        [[dataBaseHandle shareDB] deletePlayerWithTitle:playinfo.title];
        //关闭数据库
        [[dataBaseHandle shareDB] closeDB];
        //刷新数据
        [self.arr removeObjectAtIndex:indexPath.row];
        [self.collectionView reloadData];
    }
}

- (void)longPressAction:(UISwipeGestureRecognizer *)longPress
{
    self.isWobble = YES;
    [self.collectionView reloadData];
    NSLog(@"长按触发");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
